package com.qianli.cashmama.trade.repo.impl;

import com.fqgj.common.utils.CollectionUtils;
import com.google.common.collect.Maps;
import com.qianli.cashmama.trade.dao.TTaskRecordDao;
import com.qianli.cashmama.trade.domain.model.TaskRecord;
import com.qianli.cashmama.trade.entity.TTaskRecordEntity;
import com.qianli.cashmama.trade.repo.TaskRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zsp
 */
@Repository
public class TaskRecordRepositoryImpl implements TaskRecordRepository {
    @Autowired
    private TTaskRecordDao tTaskRecordDao;

    @Override
    public void store(TaskRecord taskRecord) {
        TTaskRecordEntity tTaskRecordEntity = new TTaskRecordEntity();
        tTaskRecordEntity.setTaskId(taskRecord.getTaskId());
        tTaskRecordEntity.setRequest(taskRecord.getRequest());
        tTaskRecordEntity.setResponse(taskRecord.getResponse());
        tTaskRecordDao.insert(tTaskRecordEntity);
    }

    @Override
    public void restore(TaskRecord taskRecord) {
        TTaskRecordEntity tTaskRecordEntity = new TTaskRecordEntity();
        tTaskRecordEntity.setId(taskRecord.getId());
        tTaskRecordEntity.setTaskId(taskRecord.getTaskId());
        tTaskRecordEntity.setRequest(taskRecord.getRequest());
        tTaskRecordEntity.setResponse(taskRecord.getResponse());
        tTaskRecordDao.updateByPrimaryKey(tTaskRecordEntity);
    }

    @Override
    public TaskRecord load(String taskId) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("deleted", 0);
        params.put("taskId", taskId);
        List<TTaskRecordEntity> tTaskRecordEntities = tTaskRecordDao.selectByParams(params);
        if (CollectionUtils.isEmpty(tTaskRecordEntities)) {
            return null;
        }
        List<TTaskRecordEntity> collect = tTaskRecordEntities.stream().sorted(Comparator.comparing(TTaskRecordEntity::getId).reversed())
                .collect(Collectors.toList());
        TTaskRecordEntity tTaskRecordEntity = collect.get(0);
        TaskRecord taskRecord = new TaskRecord();
        taskRecord.setId(tTaskRecordEntity.getId());
        taskRecord.setTaskId(tTaskRecordEntity.getTaskId());
        taskRecord.setRequest(tTaskRecordEntity.getRequest());
        taskRecord.setResponse(tTaskRecordEntity.getResponse());
        return taskRecord;
    }

    @Override
    public void delete(TaskRecord taskRecord) {
        TTaskRecordEntity tTaskRecordEntity = new TTaskRecordEntity();
        tTaskRecordEntity.setId(taskRecord.getId());
        tTaskRecordEntity.setDeleted(true);
        tTaskRecordDao.updateByPrimaryKey(tTaskRecordEntity);

    }
}
